<?php

namespace App\Http\Controllers;

use App\Models\Org;
use App\Models\Volunteer;
use Illuminate\Http\Request;

class StarSettingController extends Controller
{
    public function get(Request $request){
        $user = $request->user();
        $query = Org::query();
        switch ($user->type) {
            case 4:

        }
        if ($user->type == 4) {
            if (!$request->has('org_id')) {
                throw new \Exception('请指定机构信息');
            }

            $query->where('id', '=', $request->get('org_id'));
        } else if ($user->type == 3) {
            $query->where('id', '=', $user->org_id);
        } else {
            throw new \Exception('无权限访问');
        }
        $data = $query->first()->toArray();
        if ($data && isset($data['volunteer_stars_config'])) {
            $data['v1'] = $data['volunteer_stars_config']['1'];
            $data['v2'] = $data['volunteer_stars_config']['2'];
            $data['v3'] = $data['volunteer_stars_config']['3'];
            $data['v4'] = $data['volunteer_stars_config']['4'];
            $data['v5'] = $data['volunteer_stars_config']['5'];
        }
        return $this->returnJSON($data, 0, '');
    }

    public function set(Request $request) {
        $user = $request->user();
        switch ($user->type) {
            case 4:

        }
        if ($user->type == 4) {
            if (!$request->has('org_id')) {
                throw new \Exception('请指定机构信息');
            }

            $org = Org::findOrFail($request->get('org_id'));
        } else if ($user->type == 3) {
            $org = Org::findOrFail($user->org_id);
        } else {
            throw new \Exception('无权限访问');
        }
        $this->validate($request, [
            'v1' => 'required',
            'v2' => 'required',
            'v3' => 'required',
            'v4' => 'required',
            'v5' => 'required',
            't1' => 'required',
            't2' => 'required',
            't3' => 'required',
            't4' => 'required',
            't5' => 'required',
        ]);
        $data = $request->only(['open_stars', 'v1', 'v2', 'v3', 'v4', 'v5',
            't1', 't2', 't3', 't4', 't5'
        ]);
        $data['volunteer_stars_config'] = [
            '1' => $data['v1'],
            '2' => $data['v2'],
            '3' => $data['v3'],
            '4' => $data['v4'],
            '5' => $data['v5'],
        ];
        $data['team_stars_config'] = [
            '1' => $data['t1'],
            '2' => $data['t2'],
            '3' => $data['t3'],
            '4' => $data['t4'],
            '5' => $data['t5'],
        ];
        $org->fill($data);
        if ($org->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        } else {
            return $this->returnJSON(null, 403, '保存失败');
        }
    }
}
